
pub mod views;
pub mod themes;

pub use components::*;
pub use views::*;

use iced::{Element, Fill, Length};
use iced::widget::{text, text_input, scrollable, column, row, container, Space};
use iced::widget::button as iced_button;

pub mod theme;
pub mod components;
pub mod fonts;

use theme::{CdbTheme, ShadcnColors};
use components::*;
use fonts::Fonts;

/// Main GUI message types
#[derive(Debug, Clone)]
pub enum Message {
    // Connection messages
    ConnectToDatabase,
    DisconnectFromDatabase,
    ConnectionStringChanged(String),
    ConnectionResult(Result<String, String>),

    // Query messages
    QueryChanged(String),
    ExecuteQuery,
    QueryResultReceived(Result<String, String>),

    // AI messages
    AiPromptChanged(String),
    SendAiPrompt,
    AiResponseReceived(String),
    AiAssistant(components::ai_assistant::AiAssistantMessage),
    AiSqlGenerated(Result<cdb_ai::GeneratedSql, String>),

    // UI messages
    TabChanged(usize),
    ThemeChanged(String),
    SettingsOpened,
    SettingsClosed,

    // Database configuration
    DatabaseTypeChanged(String),
    HostChanged(String),
    PortChanged(String),
    DatabaseNameChanged(String),
    UsernameChanged(String),
    PasswordChanged(String),
}

/// Main GUI state
#[derive(Debug)]
pub struct CdbGui {
    // Connection state
    pub connection_string: String,
    pub is_connected: bool,
    pub connection_status: String,

    // Database configuration
    pub database_type: String,
    pub host: String,
    pub port: String,
    pub database_name: String,
    pub username: String,
    pub password: String,

    // Query state
    pub current_query: String,
    pub query_result: String,
    pub query_history: Vec<String>,

    // AI state
    pub ai_prompt: String,
    pub ai_response: String,
    pub ai_assistant: components::ai_assistant::AiAssistant,
    pub ai_engine: Option<cdb_ai::AiEngine>,

    // UI state
    pub active_tab: usize,
    pub show_settings: bool,
    pub show_connection_form: bool,
    pub theme: CdbTheme,
}

impl CdbGui {
    /// Create text with proper font support for Chinese characters
    fn create_text(content: &str) -> iced::widget::Text<'_> {
        // Use default text widget without specifying font
        // Let the system handle font selection for Chinese characters
        text(content)
    }

    /// Create text with explicit font fallback for Chinese characters
    fn create_chinese_text(content: &str) -> iced::widget::Text<'_> {
        // Use system default font which should handle Chinese characters
        // This is more reliable than specifying specific font names
        text(content)
    }

    /// Create monospace text for code/SQL
    fn create_code_text(content: &str) -> iced::widget::Text<'_> {
        text(content)
            .font(Fonts::get_monospace_font())
    }

    /// Get database object icon based on type
    pub fn get_db_object_icon(object_type: &str) -> &'static str {
        match object_type {
            "database" => "🗄️",
            "table" => "📊",
            "view" => "👁️",
            "procedure" => "⚙️",
            "function" => "🔧",
            "trigger" => "⚡",
            "index" => "📇",
            "schema" => "📁",
            "localhost" => "🖥️",
            _ => "📄",
        }
    }

    /// Create a new GUI instance
    pub fn new() -> Self {
        Self {
            connection_string: String::new(),
            is_connected: false,
            connection_status: "Disconnected".to_string(),
            database_type: "PostgreSQL".to_string(),
            host: "localhost".to_string(),
            port: "5432".to_string(),
            database_name: String::new(),
            username: String::new(),
            password: String::new(),
            current_query: "SELECT 1;".to_string(),
            query_result: String::new(),
            query_history: Vec::new(),
            ai_prompt: String::new(),
            ai_response: String::new(),
            ai_assistant: components::ai_assistant::AiAssistant::new(),
            ai_engine: Some(cdb_ai::AiEngine::new_sync()),
            active_tab: 0,
            show_settings: false,
            show_connection_form: false,
            theme: CdbTheme::dark(),
        }
    }
    
    /// Update the GUI state based on a message
    pub fn update(&mut self, message: Message) {
        match message {
            Message::ConnectToDatabase => {
                self.connection_status = "Connecting...".to_string();
                // The actual connection will be handled by the app layer
            }
            Message::DisconnectFromDatabase => {
                self.is_connected = false;
                self.connection_status = "Disconnected".to_string();
            }
            Message::ConnectionStringChanged(value) => {
                self.connection_string = value;
            }
            Message::ConnectionResult(result) => {
                match result {
                    Ok(message) => {
                        self.is_connected = true;
                        self.connection_status = message;
                    }
                    Err(error) => {
                        self.is_connected = false;
                        self.connection_status = format!("Error: {}", error);
                    }
                }
            }
            Message::QueryChanged(value) => {
                self.current_query = value;
            }
            Message::ExecuteQuery => {
                self.query_result = "Executing query...".to_string();
                // The actual execution will be handled by the app layer
            }
            Message::QueryResultReceived(result) => {
                match result {
                    Ok(result_text) => {
                        self.query_result = result_text;
                        // Add to history
                        self.query_history.push(self.current_query.clone());
                        if self.query_history.len() > 50 {
                            self.query_history.remove(0);
                        }
                    }
                    Err(error) => {
                        self.query_result = format!("Error: {}", error);
                    }
                }
            }
            Message::AiPromptChanged(value) => {
                self.ai_prompt = value;
            }
            Message::SendAiPrompt => {
                self.ai_response = "Processing AI request...".to_string();
                // The actual AI processing will be handled by the app layer
            }
            Message::AiResponseReceived(response) => {
                self.ai_response = response;
            }
            Message::TabChanged(index) => {
                self.active_tab = index;
            }
            Message::ThemeChanged(_theme) => {
                // TODO: Implement theme changing
            }
            Message::SettingsOpened => {
                self.show_settings = true;
            }
            Message::SettingsClosed => {
                self.show_settings = false;
            }
            Message::DatabaseTypeChanged(value) => {
                self.database_type = value;
                // Update default port based on database type
                self.port = match self.database_type.as_str() {
                    "PostgreSQL" => "5432".to_string(),
                    "MySQL" => "3306".to_string(),
                    "SQLite" => "".to_string(),
                    "MongoDB" => "27017".to_string(),
                    _ => self.port.clone(),
                };
            }
            Message::HostChanged(value) => {
                self.host = value;
            }
            Message::PortChanged(value) => {
                self.port = value;
            }
            Message::DatabaseNameChanged(value) => {
                self.database_name = value;
            }
            Message::UsernameChanged(value) => {
                self.username = value;
            }
            Message::PasswordChanged(value) => {
                self.password = value;
            }
            Message::AiAssistant(ai_message) => {
                if let Some(input) = self.ai_assistant.update(ai_message) {
                    // 如果AI助手返回了输入内容，说明需要生成SQL
                    if let Some(ai_engine) = &self.ai_engine {
                        // 这里应该异步调用AI引擎，但为了简化，我们先同步处理
                        // 在实际应用中，这应该发送一个命令到应用层进行异步处理
                        self.ai_prompt = input;
                    }
                }
            }
            Message::AiSqlGenerated(result) => {
                use components::ai_assistant::AiAssistantMessage;
                self.ai_assistant.update(AiAssistantMessage::SqlGenerated(result));
            }
        }
    }
    
    /// Create the main view with Chat2DB-inspired layout
    pub fn view(&self) -> Element<Message> {
        let main_layout = column![
            self.toolbar_view(),
            self.main_workspace()
        ]
        .spacing(0);

        container(main_layout)
            .style(move |_theme| {
                container::Style {
                    background: Some(self.theme.colors.background.into()),
                    border: iced::Border::default(),
                    shadow: iced::Shadow::default(),
                    text_color: None,
                }
            })
            .width(Fill)
            .height(Fill)
            .into()
    }

    /// Create the main workspace with three-panel layout
    fn main_workspace(&self) -> Element<Message> {
        row![
            self.database_explorer_panel(),
            vertical_separator(&self.theme),
            self.sql_editor_panel(),
            vertical_separator(&self.theme),
            self.ai_chat_panel()
        ]
        .spacing(0)
        .height(Fill)
        .into()
    }

    /// Create the tab bar view
    fn tab_bar_view(&self) -> Element<Message> {
        let tabs = [
            ("Connection", self.active_tab == 0),
            ("Query", self.active_tab == 1),
            ("AI Chat", self.active_tab == 2),
            ("Schema", self.active_tab == 3),
        ];

        let tab_buttons = tabs.iter().enumerate().map(|(index, (label, is_active))| {
            let mut btn = iced_button(text(*label));

            if !is_active {
                btn = btn.on_press(Message::TabChanged(index));
            }

            btn.into()
        }).collect::<Vec<Element<Message>>>();

        row(tab_buttons).spacing(5).into()
    }
    
    /// Create the toolbar view (similar to Chat2DB top toolbar)
    fn toolbar_view(&self) -> Element<Message> {
        let left_section = row![
            // Enhanced Database connection dropdown (Chat2DB style)
            container(
                row![
                    text("📊")
                        .size(typography::SM)
                        .color(self.theme.colors.primary),
                    Self::create_text("Demo data")
                        .size(typography::SM)
                        .color(self.theme.colors.foreground),
                    text("▼")
                        .size(typography::XS)
                        .color(self.theme.colors.muted_foreground),
                ]
                .spacing(spacing::XS)
                .align_y(iced::Alignment::Center)
            )
            .padding([spacing::XS, spacing::SM])
            .style(move |_theme| {
                container::Style {
                    background: Some(iced::Background::Color(iced::Color::from_rgba(0.1, 0.1, 0.1, 0.5))),
                    border: iced::Border {
                        color: self.theme.colors.border,
                        width: 1.0,
                        radius: iced::border::Radius::from(4.0),
                    },
                    ..Default::default()
                }
            }),

            // Refresh button
            modern_button(
                text("🔄"),
                ButtonVariant::Ghost,
                ButtonSize::Icon,
                &self.theme,
            )
            .on_press(Message::ConnectToDatabase),

            // New query button
            modern_button(
                text("📝"),
                ButtonVariant::Ghost,
                ButtonSize::Icon,
                &self.theme,
            )
            .on_press(Message::QueryChanged("".to_string())),
        ]
        .spacing(spacing::SM)
        .align_y(iced::Alignment::Center);

        let center_section = row![
            // Execute button (prominent like Chat2DB)
            modern_button(
                Self::create_chinese_text("▶ 执行"),
                ButtonVariant::Primary,
                ButtonSize::Medium,
                &self.theme,
            )
            .on_press(Message::ExecuteQuery),

            // Format SQL button
            modern_button(
                Self::create_chinese_text("🎨 格式化"),
                ButtonVariant::Outline,
                ButtonSize::Small,
                &self.theme,
            ),

            // Save query button
            modern_button(
                Self::create_chinese_text("💾 保存"),
                ButtonVariant::Outline,
                ButtonSize::Small,
                &self.theme,
            ),

            // Import/Export tools
            modern_button(
                Self::create_chinese_text("📤 导出"),
                ButtonVariant::Ghost,
                ButtonSize::Small,
                &self.theme,
            ),
        ]
        .spacing(spacing::SM)
        .align_y(iced::Alignment::Center);

        let right_section = row![
            // Connection status
            connection_badge(self.is_connected, &self.theme),

            // Settings
            modern_button(
                text("⚙️"),
                ButtonVariant::Ghost,
                ButtonSize::Icon,
                &self.theme,
            )
            .on_press(Message::SettingsOpened),
        ]
        .spacing(spacing::SM)
        .align_y(iced::Alignment::Center);

        let toolbar_content = row![
            left_section,
            Space::new(Length::Fill, Length::Fixed(0.0)),
            center_section,
            Space::new(Length::Fill, Length::Fixed(0.0)),
            right_section,
        ]
        .align_y(iced::Alignment::Center)
        .padding(spacing::MD);

        container(toolbar_content)
            .style(move |_theme| {
                container::Style {
                    background: Some(self.theme.colors.card.into()),
                    border: iced::Border {
                        color: self.theme.colors.border,
                        width: 1.0,
                        radius: 0.0.into(),
                    },
                    shadow: iced::Shadow {
                        color: iced::Color::from_rgba(0.0, 0.0, 0.0, 0.1),
                        offset: iced::Vector::new(0.0, 1.0),
                        blur_radius: 2.0,
                    },
                    text_color: None,
                }
            })
            .width(Fill)
            .into()
    }

    /// Create the database explorer panel (left sidebar)
    fn database_explorer_panel(&self) -> Element<Message> {
        let header = row![
            Self::create_chinese_text("数据库")
                .size(typography::SM)
                .color(self.theme.colors.muted_foreground),
            Space::new(Length::Fill, Length::Fixed(0.0)),
            modern_button(
                text("+"),
                ButtonVariant::Ghost,
                ButtonSize::Icon,
                &self.theme,
            )
            .on_press(Message::ConnectToDatabase),
        ]
        .align_y(iced::Alignment::Center)
        .padding([spacing::MD, spacing::LG]);

        let database_tree = column![
            // Demo data group
            self.database_group_item("Demo data", true),
            self.database_connection_item("localhost", true),

            // New Group
            self.database_group_item("New Group", false),
            self.database_connection_item("localhost", false),
            self.database_connection_item("localhost", false),
        ]
        .spacing(spacing::XS);

        let content = column![
            header,
            horizontal_separator(&self.theme),
            scrollable(database_tree).height(Fill),
        ]
        .spacing(0);

        container(content)
            .style(move |_theme| {
                container::Style {
                    background: Some(self.theme.colors.card.into()),
                    border: iced::Border {
                        color: self.theme.colors.border,
                        width: 1.0,
                        radius: 0.0.into(),
                    },
                    shadow: iced::Shadow::default(),
                    text_color: None,
                }
            })
            .width(Length::Fixed(280.0))
            .height(Fill)
            .into()
    }

    /// Create a database group item with enhanced icons
    fn database_group_item<'a>(&self, name: &'a str, is_expanded: bool) -> Element<'a, Message> {
        let icon = if is_expanded {
            Self::get_db_object_icon("database")
        } else {
            Self::get_db_object_icon("schema")
        };

        row![
            text(icon).size(typography::SM),
            text(name)
                .size(typography::SM)
                .color(self.theme.colors.foreground),
            Space::new(Length::Fill, Length::Fixed(0.0)),
            text(if is_expanded { "▼" } else { "▶" })
                .size(typography::XS)
                .color(self.theme.colors.muted_foreground),
        ]
        .spacing(spacing::SM)
        .align_y(iced::Alignment::Center)
        .padding([spacing::SM, spacing::LG])
        .into()
    }

    /// Create a database connection item with status indicators
    fn database_connection_item<'a>(&self, name: &'a str, is_connected: bool) -> Element<'a, Message> {
        let status_icon = if is_connected { "🟢" } else { "🔴" };
        let db_icon = Self::get_db_object_icon("localhost");

        row![
            Space::new(Length::Fixed(20.0), Length::Fixed(0.0)), // Indentation
            text(db_icon).size(typography::SM),
            text(name)
                .size(typography::SM)
                .color(if is_connected {
                    self.theme.colors.foreground
                } else {
                    self.theme.colors.muted_foreground
                }),
            Space::new(Length::Fill, Length::Fixed(0.0)),
            text(status_icon).size(typography::XS),
        ]
        .spacing(spacing::SM)
        .align_y(iced::Alignment::Center)
        .padding([spacing::SM, spacing::LG])
        .into()
    }

    /// Create the SQL editor panel (center area)
    fn sql_editor_panel(&self) -> Element<Message> {
        let tab_bar = row![
            // SQL tab
            container(
                row![
                    text("📄"),
                    text("Demo data"),
                    modern_button(
                        text("×"),
                        ButtonVariant::Ghost,
                        ButtonSize::Icon,
                        &self.theme,
                    ),
                ]
                .spacing(spacing::SM)
                .align_y(iced::Alignment::Center)
            )
            .style(move |_theme| {
                container::Style {
                    background: Some(self.theme.colors.accent.into()),
                    border: iced::Border {
                        color: self.theme.colors.border,
                        width: 1.0,
                        radius: radius::SM.into(),
                    },
                    shadow: iced::Shadow::default(),
                    text_color: None,
                }
            })
            .padding([spacing::SM, spacing::MD]),

            // Add new tab button
            modern_button(
                text("+"),
                ButtonVariant::Ghost,
                ButtonSize::Icon,
                &self.theme,
            ),
        ]
        .spacing(spacing::XS)
        .align_y(iced::Alignment::End);

        // SQL Editor area
        let sql_editor = container(
            column![
                // Line numbers and editor
                row![
                    // Line numbers
                    container(
                        column![
                            text("1").size(typography::SM).color(self.theme.colors.muted_foreground),
                        ]
                        .spacing(2)
                    )
                    .width(Length::Fixed(40.0))
                    .padding([spacing::MD, spacing::SM]),

                    // SQL input area
                    modern_text_input(
                        "输入 SQL 语句...",
                        &self.current_query,
                        InputVariant::Filled,
                        InputSize::Medium,
                        &self.theme,
                    )
                    .on_input(Message::QueryChanged)
                    .size(typography::SM),
                ]
                .height(Length::Fixed(200.0)),

                horizontal_separator(&self.theme),

                // Results area
                container(
                    if self.query_result.is_empty() {
                        Element::from(Self::create_text("执行 SQL 查询以查看结果")
                            .size(typography::SM)
                            .color(self.theme.colors.muted_foreground))
                    } else {
                        Element::from(scrollable(
                            text(&self.query_result)
                                .size(typography::SM)
                                .color(self.theme.colors.foreground)
                        )
                        .height(Fill))
                    }
                )
                .padding(spacing::LG)
                .height(Fill),
            ]
            .spacing(0)
        )
        .style(move |_theme| {
            container::Style {
                background: Some(self.theme.colors.background.into()),
                border: iced::Border {
                    color: self.theme.colors.border,
                    width: 1.0,
                    radius: 0.0.into(),
                },
                shadow: iced::Shadow::default(),
                text_color: None,
            }
        })
        .height(Fill);

        let content = column![
            tab_bar,
            sql_editor,
        ]
        .spacing(0);

        container(content)
            .width(Fill)
            .height(Fill)
            .into()
    }

    /// Create the AI chat panel (right sidebar)
    fn ai_chat_panel(&self) -> Element<Message> {
        // Use the new AI assistant component
        self.ai_assistant
            .view(&self.theme)
            .map(Message::AiAssistant)
    }



    /// Get query history
    pub fn get_history(&self) -> Vec<String> {
        self.query_history.clone()
    }

    /// Get connection configuration
    pub fn get_connection_config(&self) -> cdb_core::database::ConnectionConfig {
        use cdb_core::database::{ConnectionConfig, DatabaseType};
        use cdb_core::database::connection::SslMode;

        let database_type = match self.database_type.as_str() {
            "PostgreSQL" => DatabaseType::PostgreSQL,
            "MySQL" => DatabaseType::MySQL,
            "SQLite" => DatabaseType::SQLite,
            "MongoDB" => DatabaseType::MongoDB,
            _ => DatabaseType::PostgreSQL,
        };

        ConnectionConfig {
            name: "default".to_string(),
            database_type,
            host: self.host.clone(),
            port: self.port.parse().unwrap_or(5432),
            database: self.database_name.clone(),
            username: self.username.clone(),
            password: self.password.clone(),
            ssl_mode: SslMode::Prefer,
            connection_timeout: 30,
            max_connections: 10,
        }
    }
}

impl Default for CdbGui {
    fn default() -> Self {
        Self::new()
    }
}
